﻿// test.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "test.h"
#include <commctrl.h>
#pragma comment(lib,"comctl32.lib")
#include <shlobj.h>
#include <shellapi.h>
#include <WindowsX.h>

#pragma  comment(lib,"WS2_32.LIB")
#include <winsock2.h>
#include <atlconv.h>
#include <concrtrm.h>

#include <process.h>
#include "ServerProc.h"

#include <atlbase.h>
#include <atlconv.h>



#define MAX_LOADSTRING 100
#define MAX_QUESTION	27
struct Client
{
	SOCKET c;
	int numPlayer;
	int pos;
	char **nick;
};




// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name
SOCKET s;										//Socket server
char** nick;
int k = 0;
HANDLE *eventThreadClient;
PAINTSTRUCT ps;

int icurrentPlayer = 0;

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);
void threadClient(PVOID cli);
void thread1(PVOID hWnd);


int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_TEST, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TEST));

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TEST));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_TEST);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
	

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;
   
   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_SYSMENU | WS_CAPTION ,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LPTSTR Convert(char *str, int len)
{
	
	LPTSTR dest = new TCHAR[len+1];
	int i;
	for ( i = 0 ; i < len && str[i]!='\0' ; i++)
	{
		dest[i] = (TCHAR)str[i];
	}
	dest[i] = '\0';
	return dest;
}
HWND hButton;
HWND hEditNumMem;
HWND hEditCurMem;
HWND hListPlayer;
HFONT hFontMain;
Listview listPlayer;

void threadClient(PVOID cli)
{
	Client  *temp = (Client *)cli;
	
	int numMem = temp->numPlayer;

	ServerProc p;
	SOCKET iCli = temp->c;
	for(int i = 0 ; i < 1;i++)
	{
		// lay nickName
		char *buff = new char[100];
		int m = recv(iCli,buff,100,0);
		
		// -1 : chưa nhập , 0: nick ko hop le , -2 : trung roi
		int result = p.nickNameProc(buff,temp->nick,k);
		
		// tra ve cho nguoi dung ket qua dang ki nick name cua ho.
		switch(result)
		{
		case 1:
			{
				strcpy(temp->nick[k],buff);
				k++;
				char *luotChoi = new char[100];
				itoa(temp->pos+1,luotChoi,10);
				send(iCli,luotChoi,strlen(luotChoi),0);
				delete luotChoi;
				LPTSTR temp;
				USES_CONVERSION;
				temp = A2T(buff);
				listPlayer.AddItem(temp,0,L"waiting",k-1);
			}break;
		case 0:
			send(iCli,"0",1,0);
			i--;
			break;
		case -1:
			send(iCli,"-1",2,0);
			i--;
			break;
		case -2:
			send(iCli,"-2",2,0);
			i--;
			break;
		}
		delete buff;
	}
	
	
	SetEvent(eventThreadClient[temp->pos]);
	return;
	//wait
	/*SetEvent(eventThreadClient[temp->pos]);
	WaitForMultipleObjects(1,eventThreadClient,TRUE,INFINITE);
	MessageBox(NULL,NULL,NULL,NULL);*/
}
void thread1(PVOID arg)
{
	WSADATA wsadata;
	HWND hWnd =  (HWND)arg;
	struct sockaddr_in sai,csai; //sai :server address_in , csai: client sockaddr_in
	int sockadr_in;
	WSAStartup(MAKEWORD(2,0),&wsadata); //return = 0 -> successful !
	//socket
	s = socket(AF_INET,SOCK_STREAM,0); // AF_INET: ket noi giua nhieu may --- SOCK_STREAM: tcp --- vi` dung` sock_stream nen de protocols = 0
	//bind

	sai.sin_family = AF_INET;
	sai.sin_port = 1234;
	sai.sin_addr.s_addr = inet_addr("127.0.0.1"); 

	bind(s,(sockaddr*)&sai,sizeof(sai));
	//Lay so luong client tham gia tro choi
	//=======================================
	TCHAR mem[2];
	GetWindowText(hEditNumMem,mem,5);
	SetWindowText(hWnd,mem);
	int numMem = _wtoi(mem);
	TCHAR currentPlayer[10];
	_stprintf(currentPlayer,_T("%d \/ %d"),icurrentPlayer,numMem);
	SetWindowText(hEditCurMem,currentPlayer);
	ShowWindow(hEditCurMem,SW_SHOW);

	//Tao mang socket
	//========================================
	SOCKET *c = new SOCKET[numMem];
	for(int i = 0 ;i < numMem;i++)
	{
		c[i] = socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
	}
	//Array nickname & Array event 
	//========================================
	
	nick = new LPSTR[numMem];
	eventThreadClient = new HANDLE[numMem];

	for(int i = 0; i < numMem; i++)
	{
		nick[i] = new char[100];
		eventThreadClient[i]=CreateEvent(NULL,TRUE,FALSE,NULL);
	}
	
	//===========================================
	//Listen connect from client
	int k = 0,j=0;
	EnableWindow(hEditNumMem,FALSE);
	sockadr_in = sizeof(csai);
	
	
	Sleep(200);	
		//===========================================
		//Accept connect
		for( j = 0 ; j < numMem ;j++)
		{
			listen(s,numMem);
			c[j] = accept(s,(sockaddr *)&csai, &sockadr_in);
			if(c[j]==INVALID_SOCKET)
			{
				send(c[j],"-3",2,0);
				break;
			}
			Client *Cli = new Client;
			Cli->c = c[j];
			Cli->nick = nick;
			Cli->numPlayer = numMem;
			Cli->pos = j;
			//============================================================
			//Anounce client can register nickname and process nickname: in seperate thread
			_beginthread(threadClient,0,(void*)Cli);
			Sleep(200);	
			_stprintf(currentPlayer,_T("%d \/ %d"),++icurrentPlayer,numMem);
			SetWindowText(hEditCurMem,currentPlayer);
			
		}
	
		
	//Close all thread, and come back sequential timing game.	

	WaitForMultipleObjects(numMem,eventThreadClient,TRUE,INFINITE);
	Sleep(3000);
	//xuat hien chu~ Start
	HDC hdc = GetDC(hWnd);
	HFONT hFontS;
	hFontS = CreateFont(200,100,0,0,FW_BLACK,FALSE,FALSE,FALSE,VIETNAMESE_CHARSET,OUT_CHARACTER_PRECIS,CLIP_CHARACTER_PRECIS,
		ANTIALIASED_QUALITY,DEFAULT_PITCH | FF_SCRIPT,L"FONT_STATUS");
	SetTextColor(hdc,RGB(255,255,255));
	SetBkMode(hdc,TRANSPARENT);
	SelectObject(hdc,hFontS);
	TextOut(hdc,500,102,L"Start",5);
	ReleaseDC( hWnd,hdc);
	Sleep(2000);
	// xoa chu~ Start
	RECT mRect;
	GetWindowRect(hWnd,&mRect);
	InvalidateRect(hWnd,&mRect,TRUE);

	//Mỗi vòng do while là 1 lượt chơi ( bat dau tu 1
	int round = 0;
	BOOL repeat = TRUE;

	int roundMem = numMem;
	do{
		round++;
		int iQues = 0;
		ServerProc pickQuestion;
		
		for(int iPlayer = 0 ; iPlayer < numMem; iPlayer++)
		{
			
			
		
			listPlayer.SetItem(iPlayer,1,L"playing");
			LPTSTR test = new TCHAR [1000];
			if(nick[iPlayer]!=NULL)
			{
				_stprintf(test,_T("cau hoi thu %d"),++iQues);
				MessageBox( hWnd,test,test,NULL);

				char *question = new char[2000];
				char *result = new char[2];
				pickQuestion.loadQuestion(question,"Question.txt",iQues);

				USES_CONVERSION;
				LPTSTR test1 = new TCHAR [1000];
				test1 = A2T(question);
				//MessageBox( hWnd,test1,NULL,NULL);

				send(c[iPlayer],question,strlen(question)+1,0);
				recv(c[iPlayer],result,5,0);

				int survivalPlayer = pickQuestion.countPlayer(nick,numMem);
				if(survivalPlayer == 1 || iQues == numMem * 4 )
				{
					send(c[iPlayer],"W",2,0); // win
					repeat = FALSE;
					listPlayer.SetItem(iPlayer,1,L"win");
					break;
				}
				else
				{
					if(result[0]!=question[0] && result[0]!='N')
					{   
						
						send(c[iPlayer],"L",2,0); // lose
						listPlayer.SetItem(iPlayer,1,L"lose");
						if(iPlayer == pickQuestion.getLastPlayer(nick,numMem))
						{
							nick[iPlayer]=NULL;
							iPlayer = pickQuestion.getFirstPlayer(nick,numMem)-1;
							
						}
						else
							nick[iPlayer]=NULL;
					
					}
					else
					{
						if(result[0]!= 'N')
						{
							send(c[iPlayer],"N",2,0); 
							iPlayer--; // tra loi tiep
						}
						else
						{
							send(c[iPlayer],"T",2,0); 
							listPlayer.SetItem(iPlayer,1,L"waiting");
							if(iPlayer == pickQuestion.getLastPlayer(nick,numMem))
								iPlayer = pickQuestion.getFirstPlayer(nick,numMem)-1;
						}
					}
				}
				delete result;
				delete question;
			}	
			
		}

	}while(repeat);
	


	//van chua xoa danh sach nick
	return;
}
BOOL OnCreate(HWND hwnd, LPCREATESTRUCT lpCreateStruct)
{
	InitCommonControls();
	USES_CONVERSION;
	
	//tao list nguoi choi
	listPlayer.CreateListView(WS_VISIBLE | WS_CHILD | WS_BORDER| WS_HSCROLL | LVS_EDITLABELS 
		 | LVS_EX_TWOCLICKACTIVATE | LVS_REPORT | LVS_SHOWSELALWAYS
		,50,50,300,360,hwnd,ID_LISTPLAYER);
	listPlayer.InitColumn();
	SendMessage(listPlayer.hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0,LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);


	hEditNumMem = CreateWindow(_T("EDIT"),NULL,WS_CHILD|WS_VISIBLE| ES_NUMBER
		|WS_BORDER | ES_AUTOHSCROLL ,650,42,70,18,hwnd,NULL,hInst,NULL);

	hEditCurMem = CreateWindow(_T("STATIC"),NULL,WS_CHILD|WS_VISIBLE
		|WS_BORDER | ES_AUTOHSCROLL ,650,72,70,18,hwnd,NULL,hInst,NULL);
	ShowWindow(hEditCurMem,SW_HIDE);

	hButton = CreateWindow(_T("BUTTON"),L"Create game",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,750,43,120,20,hwnd,(HMENU)ID_BUTTON,hInst,NULL);	
	
	
	
	return TRUE;
	
}
void OnPaint(HWND hwnd)
{
	HDC hdc = BeginPaint(hwnd,&ps);

	RECT mRect;
	GetWindowRect(hwnd,&mRect);
	// create dc 1x1
	HDC hdcMem = CreateCompatibleDC(hdc);
	
	
	RECT fnRect={200,25,350,45};
	hFontMain = CreateFont(14,14,0,0,FW_BLACK,FALSE,FALSE,FALSE,VIETNAMESE_CHARSET,OUT_CHARACTER_PRECIS,CLIP_CHARACTER_PRECIS,
		ANTIALIASED_QUALITY,DEFAULT_PITCH | FF_SCRIPT,L"FONT_STATUS");
	SelectObject(hdc,hFontMain);
	
	

	// create bitmap co size theo size cua bitmap load tu source , gan no voi 
	// memory dc -> dc co' size
	// tuong duong voi dc that
	BITMAP bm;
	HBITMAP hBitMapMem= LoadBitmap(hInst,MAKEINTRESOURCE(IDB_BKGROUND));
	GetObject(hBitMapMem,sizeof(bm),&bm);
	SelectObject(hdcMem,hBitMapMem);
	
	//ve hdc memmory
	
	//copy hdc memory vao hdc that
	BitBlt(hdc,0,0,bm.bmWidth,bm.bmHeight,hdcMem,0,0,SRCCOPY);
	//xuat cac text ra man hinh
	SetTextColor(hdc,RGB(255,255,255));
	SetBkMode(hdc,TRANSPARENT);
	TextOut(hdc,400,42,L"Number of player:",17);

	TextOut(hdc,50,30,L"List player",11);
	TextOut(hdc,400,72,L"Current player  :",17);



	EndPaint(hwnd,&ps);
	
	DeleteDC(hdcMem);
	DeleteObject(hBitMapMem);
	
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	
	
	switch (message)
	{
	HANDLE_MSG(hWnd,WM_CREATE,OnCreate);
	HANDLE_MSG(hWnd,WM_PAINT,OnPaint);
	
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
	
		case ID_BUTTON:
			{
				// tao phong

				TCHAR buffer[2];
				int num;
				GetWindowText(hEditNumMem,buffer,2);
				num = _wtoi(buffer);
				if(num==0)
				{
					MessageBox(hWnd,L"\"Number of player\" invalid",L"Error",MB_OK);
					break;
				}
				EnableWindow(hButton,FALSE);
				_beginthread(thread1,0,(void *)hWnd);
				
				
				
				
			
			}break;
		case ID_BUTTON1:
			{
				
			}break;
		
			
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_DESTROY:
		DeleteObject(hFontMain);
		WSACleanup();
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
